<template>
  <div class="learning-data-analysis">
   <h2 class="section-title">用户学习数据分析</h2>
    <!-- 用户搜索区域 -->
    <div class="search-section">
      <div class="user-search">
        <el-input 
          v-model="searchInput" 
          placeholder="请输入用户名" 
          clearable
          @clear="clearSearch"
          @keyup.enter="handleSearch"
          style="width: 300px">
          <template #prepend>
            <el-icon><User /></el-icon>
          </template>
        </el-input>
        <el-button 
          type="primary" 
          class="custom-primary-button"
          @click="handleSearch"
          :loading="isLoading">
          搜索用户
        </el-button>
        <el-button 
          class="custom-reset-button"
          @click="clearSearch">
          清除搜索
        </el-button>
      </div>

      <div v-if="selectedUser" class="user-details">
        <div class="user-name">用户名: <span class="highlight">{{ selectedUser.username }}</span></div>
      </div>
    </div>

    <!-- 学习概览 -->
    <el-card class="overview-card">
      <div class="overview-header">
        <div class="header-gradient"></div>
        <h3>学习概览</h3>
      </div>

      <div class="stats-container">
        <div class="stat-item">
          <div class="stat-label">总答题量</div>
          <div class="stat-value">
            <span v-if="overviewData.totalAnswers != null">{{ overviewData.totalAnswers.toLocaleString() }}</span>
            <span v-else class="no-data">暂无数据</span>
          </div>
          <div class="stat-icon">
            <el-icon><Document /></el-icon>
          </div>
        </div>

        <div class="stat-item">
          <div class="stat-label">平均正确率</div>
          <div class="stat-value">
            <span v-if="overviewData.avgAccuracyRate != null">{{ overviewData.avgAccuracyRate.toFixed(1) + '%' }}</span>
            <span v-else class="no-data">暂无数据</span>
          </div>
          <div class="stat-icon">
            <el-icon><PieChart /></el-icon>
          </div>
        </div>

        <div class="stat-item">
          <div class="stat-label">参加考试</div>
          <div class="stat-value">
            <span v-if="overviewData.totalExams != null">{{ overviewData.totalExams.toLocaleString() }}</span>
            <span v-else class="no-data">暂无数据</span>
          </div>
          <div class="stat-icon">
            <el-icon><EditPen /></el-icon>
          </div>
        </div>

        <div class="stat-item">
          <div class="stat-label">套卷平均分</div>
          <div class="stat-value">
            <span v-if="overviewData.avgPastExamScore != null">{{ overviewData.avgPastExamScore.toFixed(2) }}</span>
            <span v-else class="no-data">暂无数据</span>
          </div>
          <div class="stat-icon">
            <el-icon><Medal /></el-icon>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 用户每日答题趋势看板 -->
    <el-card class="trend-card">
      <div class="overview-header">
        <div class="header-gradient"></div>
        <h3>近三日答题量</h3>
      </div>
      <div v-if="dailyAnswerTrend.length > 0" class="trend-chart">
        <canvas ref="trendCanvas"></canvas>
      </div>
      <div v-else class="trend-empty">
        <p>暂无答题趋势数据</p>
      </div>
    </el-card>

    <!-- 各科目完成情况 -->
    <el-card class="subject-card">
      <div class="overview-header">
        <div class="header-gradient"></div>
        <h3>各科目完成情况</h3>
      </div>
      <div v-if="subjectFinishedData.length > 0">
        <el-table :data="subjectFinishedData" stripe style="width: 100%" class="subject-table">
          <el-table-column prop="subject" label="科目" width="180" />
          <el-table-column prop="answered" label="已做题数" width="120" />
          <el-table-column prop="accuracy" label="正确率" width="150">
            <template #default="scope">
              {{ scope.row.accuracy }}%
              <el-progress 
                :percentage="scope.row.accuracy ? parseFloat(scope.row.accuracy) : 0" 
                :color="getProgressColor(parseFloat(scope.row.accuracy))"
                :show-text="false"
                :stroke-width="6"
                style="margin-top: 5px; width: 80%" />
            </template>
          </el-table-column>
          <el-table-column prop="progress" label="进度" width="180">
            <template #default="scope">
              <div class="progress-container">
                <span>{{ scope.row.progress }}%</span>
                <el-progress 
                  :percentage="scope.row.progress ? parseFloat(scope.row.progress) : 0" 
                  :color="getProgressColor(parseFloat(scope.row.progress))"
                  :stroke-width="16"
                  :text-inside="true" />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="lastActive" label="最近活跃时间" />
        </el-table>
      </div>
      <div v-else class="subject-empty">
        <p>暂无科目完成数据</p>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { User } from '@element-plus/icons-vue'
import { Chart } from 'chart.js/auto'

// 用户搜索相关
const searchInput = ref('')
const selectedUser = ref(null)
const isLoading = ref(false)

// 概览数据
const overviewData = ref({})

// 每日答题趋势数据
const dailyAnswerTrend = ref([])
const trendCanvas = ref(null)
let chartInstance = null

// 各科目完成数据
const subjectFinishedData = ref([])

// 生命周期钩子：组件卸载时销毁图表
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.destroy()
  }
})

// 获取进度条颜色
const getProgressColor = (percentage) => {
  if (percentage >= 80) return '#67c23a'; // 绿色
  if (percentage >= 60) return '#e6a23c'; // 黄色
  if (percentage >= 40) return '#6f7ad3'; // 蓝色
  return '#f56c6c'; // 红色
}

// 用户搜索
const handleSearch = async () => {
  if (!searchInput.value.trim()) {
    ElMessage.warning('请输入用户名')
    return
  }

  isLoading.value = true
  try {
    // 搜索用户
    const searchResponse = await axios.get('/api/wrong-questions/search-user', {
      params: { username: searchInput.value.trim() }
    })

    selectedUser.value = {
      userId: searchResponse.data.userId,
      username: searchResponse.data.username
    }
    ElMessage.success(`找到用户: ${searchResponse.data.username}`)

    // 获取用户学习统计数据
    const statsResponse = await axios.get(`/api/admin/statistics/user/${selectedUser.value.userId}`)
    overviewData.value = statsResponse.data

    // 获取用户每日答题趋势数据
    await fetchDailyAnswerTrend(selectedUser.value.userId)
    
    // 获取科目完成数据
    await fetchSubjectFinishedData(selectedUser.value.userId)
  } catch (error) {
    console.error('搜索用户失败:', error)
    if (error.response?.status === 404) {
      ElMessage.error('用户不存在，请检查用户名是否正确')
    } else {
      ElMessage.error('搜索用户失败: ' + (error.response?.data?.message || error.message))
    }
    selectedUser.value = null
    overviewData.value = {}
    dailyAnswerTrend.value = []
    subjectFinishedData.value = []
  } finally {
    isLoading.value = false
  }
}

// 清除搜索
const clearSearch = () => {
  searchInput.value = ''
  selectedUser.value = null
  overviewData.value = {}
  dailyAnswerTrend.value = []
  subjectFinishedData.value = []
  
  // 清除图表
  if (chartInstance) {
    chartInstance.destroy()
    chartInstance = null
  }
}

// 监听用户选择变化
watch(selectedUser, async () => {
  if (selectedUser.value) {
    try {
      const statsResponse = await axios.get(`/api/admin/statistics/user/${selectedUser.value.userId}`)
      overviewData.value = statsResponse.data

      // 获取用户每日答题趋势数据
      await fetchDailyAnswerTrend(selectedUser.value.userId)
      
      // 获取科目完成数据
      await fetchSubjectFinishedData(selectedUser.value.userId)
    } catch (error) {
      console.error('加载学习进度数据失败:', error)
      ElMessage.error('加载学习进度数据失败: ' + (error.response?.data?.message || error.message))
    }
  } else {
    overviewData.value = {}
    dailyAnswerTrend.value = []
    subjectFinishedData.value = []
    
    // 清除图表
    if (chartInstance) {
      chartInstance.destroy()
      chartInstance = null
    }
  }
})

// 获取用户每日答题趋势数据
const fetchDailyAnswerTrend = async (userId) => {
  try {
    const response = await axios.get(`/api/admin/statistics/daily-trend/${userId}`)
    // 对数据进行排序，确保日期升序（从左到右时间递增）
    const sortedData = [...(response.data.data || [])].sort((a, b) => 
      new Date(a.date) - new Date(b.date)
    );
    dailyAnswerTrend.value = sortedData;
    renderTrendChart();
  } catch (error) {
    console.error('获取每日答题趋势数据失败:', error)
    ElMessage.error('获取每日答题趋势数据失败: ' + (error.response?.data?.message || error.message))
  }
}

// 获取科目完成数据
const fetchSubjectFinishedData = async (userId) => {
  try {
    const response = await axios.get('/api/subject-finished/info', {
      params: { userId }
    })
    
    // 使用正确的字段名映射，并格式化最近活跃时间为日期格式
    subjectFinishedData.value = response.data.map(item => ({
      subject: item.subject,                // 科目名称
      answered: item.answeredCount,         // 已做题数
      accuracy: item.correctRate,           // 正确率
      progress: item.progressRate,          // 进度
      // 格式化最近活跃时间，只保留日期部分（YYYY-MM-DD）
      lastActive: item.lastActiveTime ? formatDate(item.lastActiveTime) : '无记录'
    }))
  } catch (error) {
    console.error('获取科目完成数据失败:', error)
    ElMessage.error('获取科目完成数据失败: ' + (error.response?.data?.message || error.message))
    subjectFinishedData.value = []
  }
}

// 格式化日期为 YYYY-MM-DD
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 渲染每日答题趋势图表
const renderTrendChart = () => {
  if (!trendCanvas.value || dailyAnswerTrend.value.length === 0) return
  
  const ctx = trendCanvas.value.getContext('2d')
  
  // 销毁现有图表
  if (chartInstance) {
    chartInstance.destroy()
  }
  
  // 格式化日期（已确保日期是升序）
  const dates = dailyAnswerTrend.value.map(item => {
    const date = new Date(item.date);
    return `${date.getMonth() + 1}/${date.getDate()}`;
  });
  
  const answerCounts = dailyAnswerTrend.value.map(item => item.answerCount)
  
  // 创建新图表
  chartInstance = new Chart(ctx, {
    type: 'line',
    data: {
      labels: dates,
      datasets: [{
        label: '每日答题数量',
        data: answerCounts,
        borderColor: 'rgb(75, 192, 192)',
        backgroundColor: 'rgba(75, 192, 192, 0.2)',
        borderWidth: 2,
        pointBackgroundColor: 'rgb(75, 192, 192)',
        tension: 0.3,
        fill: true
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'top',
        },
        tooltip: {
          mode: 'index',
          intersect: false,
          callbacks: {
            label: function(context) {
              return `答题数: ${context.raw}`;
            }
          }
        }
      },
      scales: {
        y: {
          beginAtZero: true,
          grid: {
            color: 'rgba(0, 0, 0, 0.05)'
          }
        },
        x: {
          grid: {
            display: false
          }
        }
      },
      animation: {
        duration: 1000,
        easing: 'easeOutQuart'
      }
    }
  })
}
</script>

<style scoped>
.section-title {
  position: relative;
  margin-bottom: 25px;
  color: #1a2f54;
  padding-bottom: 15px;
  font-weight: 600;
  font-size: 22px;
}

.section-title::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 50px;
  height: 4px;
  background: linear-gradient(90deg, #3b527a, #4e6694);
  border-radius: 2px;
}
/* 整体布局 */
.learning-data-analysis {
  padding: 20px;
  background-color: #f5f7fa;
}

h2 {
  margin-bottom: 25px;
  color: #1a2f54;
  border-bottom: 1px solid #e6e9ed;
  padding-bottom: 15px;
  font-weight: 600;
  font-size: 22px;
}

/* 搜索区域 */
.search-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.user-search {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 15px;
}

.custom-primary-button {
  /* 修改为较浅的蓝色渐变 */
  background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
  border: none;
  color: white;
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(26, 47, 84, 0.3);
}

.custom-primary-button:hover {
  /* 修改为较浅的蓝色渐变 */
  background: linear-gradient(135deg, #3b527a 0%, #4e6694 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(26, 47, 84, 0.4);
}

.custom-reset-button {
  background: #f0f2f5;
  border-color: #dcdfe6;
  color: #606266;
  transition: all 0.3s;
}

.custom-reset-button:hover {
  background: #e4e7ed;
  color: #1a2f54;
}

.user-details {
  font-size: 15px;
  color: #606266;
  padding-top: 15px;
  border-top: 1px dashed #ebeef5;
}

.user-details .highlight {
  font-weight: 600;
  color: #1a2f54;
}

/* 卡片通用样式 */
.overview-card, .trend-card, .subject-card {
  border-radius: 10px;
  margin-bottom: 24px;
  border: none;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.overview-header {
  position: relative;
  padding: 16px 20px;
  margin-bottom: 15px;
}

.overview-header h3 {
  color: white;
  position: relative;
  z-index: 2;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-gradient {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 100%;
  /* 修改为较浅的蓝色渐变 */
  background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
  z-index: 1;
}

/* 统计卡片 */
.stats-container {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}

.stat-item {
  background: white;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  transition: transform 0.3s, box-shadow 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  flex: 1;
  position: relative;
  overflow: hidden;
  /* 修改为较浅的蓝色 */
  border-top: 3px solid #4e6694;
}

.stat-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.stat-label {
  font-size: 15px;
  color: #606266;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #1a2f54;
  min-height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.stat-icon {
  position: absolute;
  top: 15px;
  right: 15px;
  color: #1a2f54;
  opacity: 0.1;
  font-size: 36px;
}

.no-data {
  font-size: 16px;
  color: #909399;
  font-weight: normal;
}

/* 趋势图表卡片 */
.trend-chart {
  height: 300px;
  padding: 15px;
}

.trend-empty {
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #f9f9f9;
  color: #909399;
  font-size: 16px;
  line-height: 1.6;
}

/* 科目表格卡片 */
.subject-card {
  padding-bottom: 20px;
}

.subject-table {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.subject-table .el-table__header) {
  background-color: #f0f5ff;
}

:deep(.subject-table .el-table th) {
  background-color: #f0f5ff;
  color: #1a2f54;
  font-weight: 600;
}

.subject-empty {
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #f9f9f9;
  color: #909399;
  font-size: 16px;
  line-height: 1.6;
}

.progress-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: flex-start;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .stats-container {
    flex-wrap: wrap;
  }
  
  .stat-item {
    flex-basis: calc(50% - 10px);
  }
}

@media (max-width: 768px) {
  .user-search {
    flex-wrap: wrap;
  }
  
  .stat-item {
    flex-basis: 100%;
  }
  
  .user-details {
    flex-direction: column;
    gap: 8px;
  }
}
</style>